package cn.hnucm.service.Impl;

import cn.hncum.feign.clients.UserClient;
import cn.hnucm.bean.TbToken;
import cn.hnucm.handler.SuccessHandler;
import cn.hnucm.pojo.User;
import cn.hnucm.service.LoginService;
import cn.hnucm.utils.JwtUtil;
import cn.hnucm.vo.UserInfo;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.DateFormat;
import java.util.*;

/**
 * @Author:liweihua
 * @Description: 用来验证用户是否正确，数据库中有用户就给他办法token
 * @Date: 17:55$ 2021/12/15/015$
 * @Modified:
 */
@Service
public class LoginServiceImpl implements LoginService {

    private DateFormat dateformatObject = DateFormat.getTimeInstance(DateFormat.MEDIUM, Locale.CHINA);

    public LoginServiceImpl(){
    }
    private User user;

    @Autowired
    UserClient userClient;

    public void setUser(User user) {
        this.user = user;
    }
    /**
     * 远程调用feign，调用userservice模块来查询用户的账号信息
     * @return
     */
    @Override
    public Map<String,Object> verifyUser() {
        Map<String,Object> R = new HashMap<>();
        //验证通过
        //先查找这个用户有没有token
        List<TbToken> userToken = findUserToken(this.user.getUserId());
        UserInfo returnInfo = user.pull();
        //创建jackson的核心对象  ObjectMApper
        ObjectMapper mapper = new ObjectMapper();
        //对象转化为json
        String json =null;
        try {
            json = mapper.writeValueAsString(returnInfo);
        }catch (Exception e){
            e.printStackTrace();
        }
        //基于工具类生成jwt令牌
        String jwt = "";
        if (userToken == null || userToken.size() == 0){
            //没有token就创建token并保存token
            TbToken token = createToken(json, this.user.getUserId());
            jwt = token.getToken();
            //保存Token
            boolean b = saveToken(token);
        }else{
            //有token就直接返回token
            jwt = userToken.get(0).getToken();
            try {
                //尝试解析token
                JwtUtil.parseJWT(jwt);
            }catch (Exception e){
                //解析失败，代表用户登录身份过期
                e.printStackTrace();
                //重新创建token
                TbToken token = createToken(json, this.user.getUserId());
                jwt = token.getToken();
                //更新Token
                boolean b = userClient.updateToken(token);
            }
        }
        R.put("jwt",jwt);
        R.put("userInfo", returnInfo);
        return R;
    }

    /**
     * 用来保存token
     * @param token
     * @return
     */
    @Override
    public boolean saveToken(TbToken token) {
        Boolean aBoolean = false;
        try {
            aBoolean = userClient.saveToken(token);
        }catch (Exception e) {
            e.printStackTrace();
        }
        return aBoolean;
    }

    /**
     * 用来找到当前登录的合法用户是否有token
     * @param id
     * @return
     */
    @Override
    public List<TbToken> findUserToken(int id) {
        List<TbToken> userToken = userClient.getUserToken(id);
        return userToken;
    }

    /**
     * 创建token对象
     * @param subject  传入用户基本信息的json数据
     * @param userId    传入token所属的用户id
     * @return
     */
    @Override
    public TbToken createToken(String subject,int userId) {
        String jwt = JwtUtil.createJWT(UUID.randomUUID().toString(), subject, null);
        //保存token
        TbToken tbToken = new TbToken();
        tbToken.setUserId(userId);
        tbToken.setToken(jwt);
        Date updateDate = new Date();
        Date expireDate = new Date();
        tbToken.setUpdateTime(updateDate);
        //默认Token过期时间是三个小时以后
        long expireHours = expireDate.getTime()+ 10800000;
        //重新设置
        expireDate.setTime(expireHours);
        tbToken.setExpireTime(expireDate);
        return tbToken;
    }
}
